package com.creditcmsplt.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * pdf转换图片工具
 * 
 * @author 雷阳军
 *
 */
public class PdfToImageUtil {
	
	private static Logger log = LoggerFactory.getLogger(PdfToImageUtil.class);

	public static void pdfConvertImage(byte[] bytes,String destPath) {
		try {
			//File file = new File("D:/20024110001191201711160009.pdf");
			PDDocument doc = PDDocument.load(bytes);
			PDFRenderer renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			List<BufferedImage> listimage=new ArrayList<BufferedImage>();
			for (int i = 0; i < pageCount; i++) {
				//image.dpi
				BufferedImage image =renderer.renderImageWithDPI(i,300); //renderer.renderImageWithDPI(i, 300F); // Windows native DPI
				if(i==0) {
					drawRect(image);
				}
				BufferedImage srcImage = resize(image, image.getWidth()/2, image.getHeight()/2);// 产生缩略图
				listimage.add(srcImage);
			}
			doc.close();
			ImageIO.write(mergeImage(false, listimage), "JPEG", new File(destPath+".jpg"));
		} catch (Exception e) {
			log.error("", e);
		}
	}
	
	public static void pdfConvertImage(String pdfPath,String destPath) {
		try {
			File file = new File(pdfPath);
			PDDocument doc = PDDocument.load(file);
			PDFRenderer renderer = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			List<BufferedImage> listimage=new ArrayList<BufferedImage>();
			for (int i = 0; i < pageCount; i++) {
				//image.dpi
				BufferedImage image =renderer.renderImageWithDPI(i,300); //renderer.renderImageWithDPI(i, 300F); // Windows native DPI
				if(i==0) {
					drawRect(image);//产生一个白色的矩形区域
				}
				BufferedImage srcImage = resize(image, image.getWidth()/2, image.getHeight()/2);// 产生缩略图
				listimage.add(srcImage);
			}
			doc.close();
			ImageIO.write(mergeImage(false, listimage), "JPEG", new File(destPath+".jpg"));
		} catch (Exception e) {
			log.error("", e);
		}
	}
	
	/**
	 * 白色填充
	 * @param image
	 */
	private static void drawRect(BufferedImage image) {
		Graphics2D graphics2d=image.createGraphics();
		graphics2d.clearRect(230,270,2000,200);
		graphics2d.setPaint(Color.WHITE);
		graphics2d.drawRect(230,270,2000,200);
		graphics2d.fillRect(230,270,2000,200);
		graphics2d.dispose();
	}

	/**
	 * 合并图片
	 * @param isHorizontal true代表水平合并，fasle代表垂直合并 
	 * @param imgs
	 * @return
	 * @throws IOException
	 */
	private static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {  
        // 生成新图片  
        BufferedImage destImage = null;  
  
        // 计算新图片的长和高  
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;  
        for (BufferedImage img : imgs) {  
            allw += img.getWidth();  
            allh += img.getHeight();  
            if (img.getWidth() > allwMax) {  
                allwMax = img.getWidth();  
            }  
            if (img.getHeight() > allhMax) {  
                allhMax = img.getHeight();  
            }  
        }  
        // 创建新图片  
        if (isHorizontal) {  
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);  
        } else {  
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);  
        }  
        
        // 合并所有子图片到新图片  
        int wx = 0, wy = 0;  
        for (int i = 0; i < imgs.size(); i++) {  
            BufferedImage img = imgs.get(i);  
            int w1 = img.getWidth();  
            int h1 = img.getHeight();  
            // 从图片中读取RGB  
            int[] ImageArrayOne = new int[w1 * h1];  
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中  
            if (isHorizontal) { // 水平方向合并  
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB  
            } else { // 垂直方向合并  
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB  
            }  
            wx += w1;  
            wy += h1;  
        }  
        return destImage;  
    }  
	
	private static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		if (sx > sy) {
			sx = sy;
			targetW = (int) (sx * source.getWidth());
		} else {
			sy = sx;
			targetH = (int) (sy * source.getHeight());
		}
		if (type == BufferedImage.TYPE_CUSTOM) {
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else {
			target = new BufferedImage(targetW, targetH, type);
		}
		Graphics2D g = target.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}
	
	public static void main(String[] args) {
		PdfToImageUtil.pdfConvertImage("D:/珠海金服 执照 .pdf", "D:/ddddd");
	}
}
